const Router = require('koa-router')

const mysql = require('mysql')

const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'koatest',
    password : '123456',
    database : 'host' // 数据库的名字
});

connection.connect()


const route = new Router()

route.get('/api/list', async(ctx, next) => {
    try {
        const res = await new Promise((resolve, reject) => {
            connection.query('select * from good', function(err, results) {
                if (err) {
                    reject(err)
                }
                resolve(results)
            })
        })
        ctx.response.body = {
            code: 1,
            data: res.sort((a, b) => {
                return b.mark -a.mark
            })
        }
    } catch(err) {
        // console.log('错误', err.message)
        ctx.response.body = {
            code: 0,
            msg: err.message
        }
    }
})

route.post('/api/vote', async(ctx, next) =>{
    try{
        // 评分的
        // 修改数据库
        const { id, mark } = ctx.request.body
        const oldMark = await new Promise((resolve, reject) => {
            connection.query(`select mark from good where id=${id}`,function(err, result) {
                if(err) reject(err)
                resolve(result)
            })
        })
        console.log(123, oldMark[0].mark)
        await new Promise((resolve, reject) => {
            connection.query('update good set mark=? where id=?', [1+Number(oldMark[0].mark), id], function(err, results){
                if (err) reject(err)
                resolve(results)
            })
        })
        ctx.response.body = {
            code: 1,
            msg: '请求成功'
        }
    }catch(e) {
        ctx.response.body = {
            code: 0,
            msg: e.message
        }
    }
    
})
module.exports = route